import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '../store/store'

/**
 * 加载遮罩层
 */
let loading
const startLoad = () => {
  loading = Loading.service({
    lock: true, // 是否锁屏
    text: '加载中...', // 加载动画的文字
    spinner: 'el-icon-loading', // 引入的loading图标
    background: 'rgba(0, 0, 0, 0.5)' // 背景颜色
  })
}

const closeLoad = () => {
  loading.close()
}

// const baseUrl = 'http://192.168.0.85:9899/api/'
const baseUrl = '/api/'

// if(process.env.NODE_ENV === 'development') {
//    axios.defaults.baseUrl = ''
// } else if(process.env.NODE_ENV === 'debug') {
//     axios.defaults.baseUrl = ''
// } else if(process.env.NODE_ENV === 'production') {
//     axios.defaults.baseUrl = ''
// }

axios.defaults.baseUrl = baseUrl
// axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'

/**
 * request拦截器
 */
axios.interceptors.request.use(config => {
  startLoad()
  const Config = config
  // Config.headers['authorization'] = 'Bearer ' + store.state.token
  store.state.token && (Config.headers.authorization = 'Bearer ' + store.state.token)
  return Config
}, err => {
  return Promise.err(err)
})

/**
 * response拦截器
 */
axios.interceptors.response.use(res => {
  closeLoad()
  if (res.status === 200) {
    return Promise.resolve(res)
  }
  return Promise.reject(res)
}, err => {
  closeLoad()
  if (err.response.status) {
    switch (err.response.status) {
      case 404:
        console.log('1111')
        break
      default:
        console.log('2222')
        break
    }
    return Promise.reject(err.response)
  }
})

/**
 * get请求
 * @param url
 * @param params
 * @returns {Promise<any>}
 */
export function sendGet (url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {params: params})
      .then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
  })
}

/**
 * sendPost 方法，对应post请求
 * @param {String} url[请求的url地址]
 * @param {Object} params[请求时携带的参数]
 * @returns {Promise<any>}
 */
export function sendPost (url, params = {}) {
  // const data = {
  //   ...params,
  //   termIP: '127.0.0.1'
  // }
  // console.log(params)
  return new Promise((resolve, reject) => {
    axios.post(`${baseUrl}${url}`, JSON.stringify(params))
      .then(res => {
        // console.log(res)
        if (res.data.retCode === 'IOP0000000') {
          resolve(res.data)
        } else {
          Message.error(res.data.message)
          reject(res.data)
        }
      }).catch(err => {
        reject(err.data)
      })
  })
}
